<template>
	<el-dialog :title="title" v-model="dialogVisible" class="redius8" width="1200" center :before-close="handleClose">
		<el-scrollbar style="height: 700px;">
			<el-form :model="form" :rules="rules" ref="queryRef" :inline="true" label-width="106px">
				<div class="bgWhite radius8">
					<div class="p20">
						<div class="fb fs16 color333 mb30 pl10">
							基础信息
						</div>
						<el-form-item label="套餐名称" prop="packageName">
							<el-tooltip class="item" effect="dark"
								:disabled="form.packageName.length > 30 ? false : true" :content="form.packageName"
								placement="top">
								<el-input size="large" :disabled="disabled" v-model="form.packageName" minlength="3" maxlength="50"
									style="width: 380px" placeholder="请填写" />
							</el-tooltip>
						</el-form-item>
						<el-form-item label="销售渠道" prop="salesChannel1">
							<div style="width: 250px;">
								<el-checkbox-group :disabled="disabled" v-model="form.salesChannel1">
									<el-checkbox v-for="dict in bus_channel" :key="dict.value" :label="dict.value"
										:value="dict.value" size="large">
										{{dict.label}}
									</el-checkbox>
								</el-checkbox-group>
							</div>
						</el-form-item>
					</div>
					<div class="p20">
						<div class="fb mb30 pl10 flex col-center row-between">
							<span class="fs16 color333">关联商品</span>							
							<div class="flex col-center">
								<el-form-item label="整件数量(套)" prop="total" style="margin-bottom: 0;margin-right: 15px;">
									<el-input type="number" :disabled="disabled" size="large" v-model="form.total" style="width: 248px"
										placeholder="请填写" />
								</el-form-item>
								<el-button type="defaultBtn" v-if="!disabled" @click="handleAdd" style="height: 38px;">
									添加商品
								</el-button>
							</div>
						</div>
						<el-table :data="form.commodityList" style="width: 100%;"
							:header-row-style="{background:'#FAFAFA',color:'#0C1019',height:'54px'}"
							:cell-style="{height:'54px'}">
							<el-table-column label="商品名称" align="center" width="250px">
								<template #default="scope">
									{{scope.row.commodityName}}
								</template>
							</el-table-column>
							<el-table-column label="商品编码" align="center" width="250px">
								<template #default="scope">
									{{scope.row.commodityNumber}}
								</template>
							</el-table-column>
							<el-table-column label="商品规格" align="center" width="250px">
								<template #default="scope">
									<dict-tag :options="bus_product_specification_unit"
										:value="scope.row.commoditySpecification*1" />
								</template>
							</el-table-column>
							<el-table-column label="数量" align="center">
								<template #default="scope">
									<el-form-item :prop="'selectList.' + scope.$index + '.quantity'">
										<el-input :disabled="disabled" type="number" v-model="scope.row.quantity" style="width: 120px"
											size="large" @input="quantityChange(scope.row.quantity,scope.$index)"
											placeholder="请输入" />
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column fixed="right" label="操作" align="center"
								class-name="small-padding fixed-width" v-if="!disabled">
								<template #default="scope">
									<span class="color-red cursor" @click="delGoods(scope.$index)">删除</span>
								</template>
							</el-table-column>
						</el-table>
					</div>
					<div class="pl20 pr20 mt30">
						<div class=" mb20 pl10 flex col-center row-between">
							<span class="fb fs16 color333">线上渠道价格</span>
							<div class="fs16 color2">
								<span class="mr10">拆箱套餐价格：{{boxPrice || 0}}元/套</span>
								<span>整件套餐价格：{{form.packagePrice || 0}}元/件</span>
							</div>
						</div>
						<el-table :data="form.commodityList" style="width: 100%;"
							:header-row-style="{background:'#FAFAFA',color:'#0C1019',height:'54px'}"
							:cell-style="{height:'54px'}">
							<el-table-column label="商品名称" align="center" width="250px">
								<template #default="scope">
									{{scope.row.commodityName}}
								</template>
							</el-table-column>
							<el-table-column label="商品编码" align="center" width="250px">
								<template #default="scope">
									{{scope.row.commodityNumber}}
								</template>
							</el-table-column>
							<el-table-column label="商品规格" align="center" width="250px">
								<template #default="scope">
									<dict-tag :options="bus_product_specification_unit"
										:value="scope.row.commoditySpecification*1" />
								</template>
							</el-table-column>
							<el-table-column label="数量" align="center" width="250px">
								<template #default="scope">
									<el-form-item :prop="'form.commodityList.' + scope.$index + '.quantity'">
										<el-input :disabled="disabled" type="number" v-model="scope.row.quantity" style="width: 120px"
											size="large" @input="quantityChange(scope.row.quantity,scope.$index)"
											min="1" placeholder="请输入" />
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column label="拆箱价格（元/最小单位）" align="center" width="250px">
								<template #default="scope">
									<el-form-item
										:prop="'form.commodityList.' + scope.$index + '.onlineIndividualPrice'">
										<el-input :disabled="disabled" type="number" v-model="scope.row.onlineIndividualPrice"
											style="width: 120px" size="large" @input="changPrice1" placeholder="请输入" />
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column label="整件价格（元/最小单位）" align="center" width="250px">
								<template #default="scope">
									<el-form-item :prop="'form.commodityList.' + scope.$index + '.onlineWholePrice'">
										<el-input :disabled="disabled" type="number" v-model="scope.row.onlineWholePrice"
											style="width: 120px" size="large" @input="changPrice1" placeholder="请输入" />
									</el-form-item>

								</template>
							</el-table-column>
							<el-table-column fixed="right" label="操作" align="center"
								class-name="small-padding fixed-width" width="250px" v-if="!disabled">
								<template #default="scope">
									<span class="color-red cursor" @click="delGoods(scope.$index)">删除</span>
								</template>
							</el-table-column>
						</el-table>
					</div>
					<div class="p20 mt20">
						<div class="fb mb20 pl10 flex col-center row-between">
							<span class="fs16 color333">线下渠道价格</span>
							<el-button type="defaultBtn" @click="handleAddPriceList" style="height: 38px;" v-if="!disabled">
								添加
							</el-button>
						</div>
						<el-table :data="form.offlinePriceList" style="width: 100%;"
							:header-row-style="{background:'#FAFAFA',color:'#0C1019',height:'54px'}"
							:cell-style="{height:'54px'}">
							<el-table-column label="价格规则" align="center" width="250px">
								<template #default="scope">
									价格规则{{scope.$index+1}}
								</template>
							</el-table-column>
							<!-- <el-table-column :label="'商品'+(j+1)+'出厂价'" align="center" width="250px" 
						v-for="(item,j) in selectList" :key="j"
						>
							<template #default="scope">
								<el-input type="number" v-model="item.outPrice" style="width: 120px" size="large"
									placeholder="请输入" />
							</template>
						</el-table-column> -->
							<el-table-column :label="'商品'+(j+1)+'出厂价'" align="center" width="250px"
								v-for="(item,j) in form.commodityList" :key="j">
								<template #default="scope">
									<el-input :disabled="disabled" type="number" v-model="scope.row.price1[j]" style="width: 120px"
										size="large" placeholder="请输入" />
								</template>
							</el-table-column>
							<el-table-column label="套餐价格" align="center" width="250px">
								<template #default="scope">
									<el-input :disabled="disabled" type="number" v-model="scope.row.packagePrice" style="width: 120px"
										size="large" placeholder="请输入" />
								</template>
							</el-table-column>
							<el-table-column label="应用范围" align="center" width="550px">
								<template #default="scope">
									<div class="flex col-center" style="width: 550px;">
										此规则应用范围：
										<div v-if="scope.$index == 0">
											此规则应用范围：全部部门（特殊部门除外）
										</div>
										<el-tree-select :disabled="disabled" v-else size="large" 
										v-model="scope.row.departmentIds1"
											:data="deptOptions" :multiple="true" :props="{
									   value: 'deptId',
									   label: 'deptName',
									   children: 'children',
									}" placeholder="请选择" value-key="deptId" show-checkbox style="width: 400px;" />
									</div>
								</template>
							</el-table-column>
							<el-table-column fixed="right" label="操作" align="center"
								class-name="small-padding fixed-width" v-if="!disabled">
								<template #default="scope">
									<span class="color-red cursor" v-if="scope.$index > 0"
										@click="delRuler(scope.$index)">删除</span>
								</template>
							</el-table-column>
						</el-table>
						<br>
						<el-form-item label="备注信息" prop="remark" label-width="106">
							<el-input :disabled="disabled" size="large" type="textarea" resize="none" class="textReset" style="width: 575px;"
								:rows="5" v-model="form.remark" placeholder="请输入信息" />
						</el-form-item>
					</div>
				</div>
			</el-form>
		</el-scrollbar>
		<div class="text-center mt25" v-if="!disabled">
			<el-button type="defaultBtn" @click="submitProduct('queryRef')" style="height: 38px;">
				{{form.id == '' ? '创建' :'编辑'}}套餐
			</el-button>
			<el-button type="operate" style="width: 88px;height: 38px;" v-if="id == ''"
				@click="resetQuery()">重 置</el-button>
			<el-button style="width: 88px;height: 38px;" @click="dialogVisible = false">取 消</el-button>
		</div>
		<!-- 添加商品 -->
		<addGiftList ref="giftPop" @getGift="selectGift"></addGiftList>
	</el-dialog>
</template>
<script>
	import {
		listGoods, //商品列表
		addPackage, //添加套餐
		getGoodsGroup, //查询商品组
		editPackage, //编辑套餐
		getPackage, //套餐详情
	} from "@/api/business/product";
	import {
		listDept, //査部门
	} from "@/api/system/dept";
	import {
		getCustomerDetail
	} from "@/api/business/customer";
	import {
		getDivisions
	} from "@/api/business/opportunity";
	import {
		getOpportunityInfo,
		listOpportunity,
		teamAllocation,
		teamReceive,
		getUserListData
	} from "@/api/business/teamOpportunity";
	import {
		resetForm,
	} from '@/utils/ruoyi'
	import addGiftList from '@/components/addGift/index.vue'//添加商品
	export default {
		components:{
			addGiftList
		},
		data() {
			return {
				bus_product_type:this.useDict('bus_product_type').bus_product_type, //产品类型
				bus_product_category:this.useDict('bus_product_category').bus_product_category, //产品类别
				bus_toxicity:this.useDict('bus_toxicity').bus_toxicity, //毒性
				bus_sosage_form:this.useDict('bus_sosage_form').bus_sosage_form, //剂型
				bus_control_object:this.useDict('bus_control_object').bus_control_object, //防治对象
				bus_application_mode:this.useDict('bus_application_mode').bus_application_mode, //施用方式
				bus_target:this.useDict('bus_target').bus_target, //靶标
				bus_channel:this.useDict('bus_channel').bus_channel, //渠道
				bus_active_ingredient_content:this.useDict('bus_active_ingredient_content').bus_active_ingredient_content, //单位
				bus_product_specification_unit:this.useDict('bus_product_specification_unit').bus_product_specification_unit, //规格
				title: '',
				dialogVisible: false,
				ids: [],
				form: {
					id: '',
					packageName: '', //套餐名称
					packagePrice: '', //套餐价格
					productCategory: '', //商品种类
					salesChannel: '', //销售渠道
					salesChannel1: [],
					total: '', //整件数量
					remark: '', //备注
					commodityList: [],
					offlinePriceList: [{
						packageId: '', //套餐id
						commodityId: '', //商品id
						priceName: '', //价格名称
						price: [], //套餐价格
						price1: [], //套餐价格
						priceArr: [],
						packagePrice: '', //套餐价格
						departmentIds: 0, //应用范围部门逗号，0全部
						departmentIds1: 0, //应用范围部门逗号，0全部
						closeRemark: '', //结束订单备注
					}],
				},
				rules: {
					packageName: [{
						required: true,
						message: '请输入套餐名称',
						trigger: 'blur'
					}],
					salesChannel1: [{
						required: true,
						message: '请选择销售渠道',
						trigger: 'change'
					}],
					total: [{
						required: true,
						message: '请输入',
						trigger: 'blur'
					}],
					quantity1: [{
						required: true,
						message: '请输入',
						trigger: 'blur'
					}, ],
					quantity: [{
						required: true,
						message: '请输入',
						trigger: 'blur'
					}, ],
					onlineIndividualPrice: [{
						required: true,
						message: '请输入',
						trigger: 'blur'
					}, ],
					onlineWholePrice: [{
						required: true,
						message: '请输入',
						trigger: 'blur'
					}, ],
				},
				list: [],
				loading: false,
				teamOptions: '', //业务经理
				cropNameArr: [], //作物名称
				productList: [], //产品名称
				options: [],
				value: [],
				loading1: false,
				selectList: [], //选中的商品
				boxPrice: 0, //拆箱价格
				deptOptions: [], //部门列表
				disabled:''
			}
		},
		// created() {
		// 	this.getUserList()
		// 	// 选中的商品信息
		// 	this.ids = localStorage.getItem('ids') ? JSON.parse(localStorage.getItem('ids')) : []
		// 	let getForm = localStorage.getItem('form')
		// 	if (getForm) {
		// 		this.form = JSON.parse(localStorage.getItem('form'))
		// 		localStorage.removeItem('form')
		// 	}
		// 	if (this.ids.length > 0) {
		// 		setTimeout(() => {
		// 			this.getGoodsGroupList(this.ids.join(','))
		// 		}, 200)
		// 		localStorage.removeItem('ids')
		// 	}

		// 	this.form.id = this.$route.query.id ? this.$route.query.id : ''
		// 	if (this.form.id != '' && !getForm) {
		// 		const obj = Object.assign({}, this.$route, {
		// 			title: "编辑套餐"
		// 		});
		// 		this.$tab.updatePage(obj);
		// 		//获取详情
		// 		this.getDetail()
		// 	} else {
		// 		const obj = Object.assign({}, this.$route, {
		// 			title: "添加套餐"
		// 		});
		// 		this.$tab.updatePage(obj);
		// 	}

		// },
		created() {
			this.getUserList()
		},
		methods: {
			handleClose(){
				this.dialogVisible = false
			},
			open(num,disabled){
				this.disabled = disabled
				if(this.resetQuery()){
					if(num == ''){
						this.title = '新增套餐'
					}else if(num !='' && !disabled){
						this.title = '编辑套餐'
						this.form.id = num
						this.getDetail()
					}else{
						this.title = '套餐详情'
						this.form.id = num
						this.getDetail()
					}
					this.dialogVisible = true
				}
			},
			//选中商品
			selectGift(e){
				for(let key in this.form.commodityList){
					for(let j in e){
						if(this.form.commodityList[key].commodityId == e[j]){
							e.splice(j,1)
						}
					}
				}
				if(e.length > 0){
					this.getGoodsGroupList(e,1)
				}
			},
			getGoodsGroupList(ids) {
				getGoodsGroup(ids).then((response) => {
					let commodityList = this.form.commodityList
					this.selectList = response.data
					// this.form.commodityList.concat(response.data)
					// this.form.commodityList = this.form.commodityList.concat(response.data)
					// console.log(this.form.commodityList,'this.form.commodityList')
					// this.$forceUpdate()
					// if(this.form.commodityList.length > 0 && this.form.id == ''){
					let arr = []
					for (let i in this.selectList) {
						let item = {
							packageId: '', //套餐id
							packageNumber: '', //套餐编号
							commodityId: '', //商品id
							commodityNumber: '', //商品编号
							commodityName: '', //商品名称
							commoditySpecification: '', //商品规格
							quantity: '', //数量
							onlineIndividualPrice: '', //线上拆箱价格
							onlineWholePrice: '', //线上整件价格
							offlinePriceJson: '', //线下商品价格数据，因价格和商品都是动态
							remark: '', //备注
						}
						arr.push(item)
						this.form.commodityList = arr
						for (let key in this.form.commodityList) {
							this.form.commodityList[key].commodityId = this.selectList[key].id //商品id
							this.form.commodityList[key].commodityName = this.selectList[key].commodityName
							this.form.commodityList[key].commodityNumber = this.selectList[key].commodityNumber
							this.form.commodityList[key].commoditySpecification = this.selectList[key]
								.specificationId //规格
							this.form.commodityList[key].offlinePriceJson = JSON.stringify(this.selectList[key]
								.offlinePrices)
						}
					}
					//  }else{
					//   this.changPrice1()
					// for(let i in this.form.commodityList){
					// this.selectList[i].quantity = this.form.commodityList[i].quantity
					//  }
					//  let arr = this.form.offlinePriceList[0].price.split(',')
					// for(let i in arr){
					// this.selectList[i].outPrice = arr[i] 
					//  } 
					//  }
					this.form.commodityList = commodityList.concat(this.form.commodityList)
					this.$forceUpdate()
				})
			},
			//获取部门
			getUserList() {
				listDept().then((response) => {
					this.deptOptions = this.handleTree(response.data, "deptId");
					console.log(this.deptOptions, 'this.deptOptions')
				});
			},
			//数量联动
			quantityChange(value, index) {
				this.form.commodityList[index].quantity = value
			},
			// 动态价格计算
			changPrice1() {
				let boxPrice = 0
				let wholePrice = 0
				for (let key in this.form.commodityList) {
					boxPrice += this.form.commodityList[key].onlineIndividualPrice * 1
				}
				this.boxPrice = boxPrice
				for (let key in this.form.commodityList) {
					wholePrice += this.form.commodityList[key].onlineWholePrice * 1
				}
				this.form.packagePrice = wholePrice
			},
			listGoods() {
				listGoods().then(res => {
					this.options = res.rows
					this.getDetail()
				})
			},
			closePage() {
				this.$tab.closePage();
			},
			// 重置
			resetQuery() {
				this.form = {
					id: '',
					packageName: '', //套餐名称
					packagePrice: '', //套餐价格
					productCategory: '', //商品种类
					salesChannel: '', //销售渠道
					salesChannel1: [],
					total: '', //整件数量
					remark: '', //备注
					commodityList: [],
					offlinePriceList: [{
						packageId: '', //套餐id
						commodityId: '', //商品id
						priceName: '', //价格名称
						price: [], //套餐价格
						price1: [], //套餐价格
						priceArr: [],
						packagePrice: '', //套餐价格
						departmentIds: 0, //应用范围部门逗号，0全部
						departmentIds1: 0, //应用范围部门逗号，0全部
						closeRemark: '', //结束订单备注
					}],
				}
				return true
			},
			// 详情
			getDetail() {
				getPackage(this.form.id).then(res => {
					this.form = res.data
					let arr = []
					for (let key in this.form.offlinePriceList) {
						this.form.offlinePriceList[key].departmentIds1 = this.form.offlinePriceList[key]
							.departmentIds.split(',')
						this.form.offlinePriceList[key].price1 = this.form.offlinePriceList[key].price.split(',')
					}
					for (let key in this.form.commodityList) {
						arr.push(this.form.commodityList[key].commodityId)

					}
					this.form.salesChannel1 = this.form.salesChannel == '' ? [] : this.form.salesChannel.split(',')
					this.changPrice1()
					// if(this.ids.length  == 0){
					// 	this.getGoodsGroupList(arr.join(','))
					// }
				})
			},
			//添加
			submitProduct(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						if (this.form.commodityList.length == 0) {
							this.$modal.msgError('请添加关联商品')
							return false;
						}
						if (this.form.salesChannel1.includes('1001') && this.form.salesChannel1.includes('1002')) {
							if (!this.submitRules1()) {
								return false;
							} else if (!this.submitRules2()) {
								return false;
							}
						} else if (this.form.salesChannel1.includes('1001')) {
							if (!this.submitRules1()) {
								return false;
							}
						} else if (this.form.salesChannel1.includes('1002')) {
							// 线下
							if (!this.submitRules2()) {
								return false;
							}
						}
						// 商品id
						let goodsIdArr = []
						//价格
						let arr = []
						for (let i in this.form.commodityList) {
							for (let key in this.form.offlinePriceList) {
								this.form.offlinePriceList[key].price = this.form.offlinePriceList[key].price1.join(',')
								goodsIdArr.push(this.form.commodityList[key].id)
								this.form.offlinePriceList[key].priceName = "价格规则" + (key * 1 + 1)
								this.form.offlinePriceList[key].commodityId = goodsIdArr.join(',')
								//第一个为全部部门，第二个及之后的转化
								if (this.form.offlinePriceList.length > 1) {
									this.form.offlinePriceList[key].departmentIds = this.form.offlinePriceList[key]
										.departmentIds1.join(',')
								}
							}
						}
						//默认第一条规则适用所有部门
						this.form.offlinePriceList[0].departmentIds = 0
						this.form.productCategory = this.form.commodityList.length //多少个商品
						this.form.salesChannel = this.form.salesChannel1.join(',')
						// 新增
						if (this.form.id == '') {
							addPackage(this.form).then(response => {
								this.$modal.msgSuccess('添加成功')
								this.handleClose()
								this.$emit('refreshList')
							})
						} else {
							// 编辑
							editPackage(this.form).then(response => {
								this.$modal.msgSuccess('编辑成功')
								this.handleClose()
								this.$emit('refreshList')
							})
						}
					} else {
						return false;
					}
				});
			},
			//提交验证
			submitRules1() {
				// 线上渠道价格
				for (let key in this.form.commodityList) {
					if (!this.form.commodityList[key].quantity || this.form.commodityList[key]
						.quantity == 0) {
						this.$modal.msgError('请补全输入关联商品数量')
						return false;
					} else if (!this.form.commodityList[key].onlineIndividualPrice || this.form
						.commodityList[key].onlineIndividualPrice == 0) {
						this.$modal.msgError('请补全输入线上渠道拆箱价格')
						return false;
					} else if (!this.form.commodityList[key].onlineWholePrice || this.form
						.commodityList[key].onlineWholePrice == 0) {
						this.$modal.msgError('请补全输入线上渠道整件价格')
						return false;
					} else {
						return true
					}
				}
			},
			//线下价格
			submitRules2() {
				for (let key in this.form.offlinePriceList) {
					if (this.form.offlinePriceList[key].price1.length == 0 || this.form
						.offlinePriceList[key].price1.length != this.form.commodityList.length) {
						this.$modal.msgError('请补全输入线下渠道商品出厂价')
						return false;
					}
					for (let j in this.form.offlinePriceList[key].price1) {
						if (!this.form.offlinePriceList[key].price1[j] || this.form
							.offlinePriceList[key].price1[j] * 1 == 0) {
							this.$modal.msgError('请确认输入线下渠道商品出厂价')
							return false;
						}
					}
					if (!this.form.offlinePriceList[key].packagePrice || this.form
						.offlinePriceList[key].packagePrice == 0) {
						this.$modal.msgError('请补全输入线下渠道商品套餐价格')
						return false;
					} else {
						return true
					}
					//  else if (this.form.offlinePriceList.length > 0 && this.form.offlinePriceList[key+1].departmentIds1.length == 0) {
					// 	this.$modal.msgError('请补全选择应用范围')
					// 	return false;
					// }

				}
			},
			//删除商品
			delGoods(index) {
				this.ids.splice(index, 1)
				this.form.commodityList.splice(index, 1)
				this.changPrice1()
				localStorage.setItem('ids', this.ids.splice(','))
			},


			// 删除规则
			delRuler(index) {
				this.form.offlinePriceList.splice(index, 1);
			},
			handleAdd() {
				// localStorage.setItem('form', JSON.stringify(this.form))
				// this.$router.push('/goods/addGoodsList')
				this.$refs.giftPop.open(1)
			},
			handleAddPriceList() {
				let item = {
					packageId: '', //套餐id
					commodityId: '', //商品id
					priceName: '', //价格名称
					price: [], //套餐名称
					price1: [], //套餐价格
					packagePrice: '', //套餐价格
					departmentIds: [], //应用范围部门逗号，0全部
					departmentIds1: [], //应用范围部门逗号，0全部
					closeRemark: '', //结束订单备注
				}
				this.form.offlinePriceList.push(item)
			}
		}
	}
</script>

<style>
	.avatar-uploader .el-upload {
		background: #F7F8FA;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
		width: 110px;
		height: 110px;
		text-align: center;
		line-height: 22px;
		color: #8c939d;
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		text-align: center;
	}

	.shopImg {
		width: 110px;
		height: 110px;
	}
</style>